package com.tjp.mall.member.service.impl;

import com.tjp.mall.member.entity.MemberLevelEntity;
import com.tjp.mall.member.exception.PhoneExistException;
import com.tjp.mall.member.exception.UserNameException;
import com.tjp.mall.member.service.MemberLevelService;
import com.tjp.mall.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tjp.common.utils.PageUtils;
import com.tjp.common.utils.Query;

import com.tjp.mall.member.dao.MemberDao;
import com.tjp.mall.member.entity.MemberEntity;
import com.tjp.mall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo memberRegisterVo) throws PhoneExistException, UserNameException {
        MemberEntity entity = new MemberEntity();

        //设置会员等级
        MemberLevelEntity memberLevelEntity =  memberLevelService.queryMemberLevelInfo();
        entity.setLevelId(memberLevelEntity.getId());

        entity.setUsername(memberRegisterVo.getUserName());
        entity.setMobile(memberRegisterVo.getPhone());
        //密码加密处理
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(memberRegisterVo.getPassword());
        //需要对密码做加密处理
        entity.setPassword(encode);

        //对应的手机号和账号不能重复
        checkUserNameUnique(memberRegisterVo.getUserName());
        checkUserPhoneUnique(memberRegisterVo.getPhone());

        this.save(entity);
    }

    private void checkUserPhoneUnique(String phone) throws PhoneExistException {
        //如果存在抛出电话异常
        int mobile = this.count(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile > 0) {
            throw new PhoneExistException();
        }
    }

    private void checkUserNameUnique(String userName) throws UserNameException {
        int username = this.count(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (username > 0) {
            throw new UserNameException();
        }
    }
}